#!/usr/bin/env python3 
# -*- coding: utf-8 -*- 
###----------1、文件说明----------### 
''' 
* 说明：conan安装配置文件
* 时间：
* 文件：
* 作者：Smile
* 版本：0.1
* 模板版本: 0.2
 - 0.2 添加 source validate finalize等函数，修改获取系统信息功能的代码存放位置
* 库版本: 
 - conan: 2.14.0
* 备注： 
'''
import os,sys
from conan import ConanFile
from conan.tools.cmake import CMakeToolchain, CMake, cmake_layout, CMakeDeps
from conan.tools.system import package_manager
from pprint import pprint
import platform
import importlib
from datetime import datetime
import time
import shutil

def getClassValue(sclass):
    '''
    获取类的子属性
    版本: 0.1
    :param sclass:
    :return:
    '''
    from types import FunctionType, BuiltinFunctionType, MethodType

    print("Get Class ", type(sclass))
    for i in dir(sclass):
        tmp = getattr(sclass, i)
        if isinstance(tmp, FunctionType) or isinstance(tmp, BuiltinFunctionType):
            print(i, "\t", type(tmp), "Function")
        else:
            print(i, "\t", type(tmp), tmp)

manager_mapping = {"Apt": ["Linux", "ubuntu", "kylin", "debian", "raspbian", "linuxmint", 'astra', 'elbrus', 'altlinux', 'pop'],
                    "Apk": ["alpine"],
                    "Yum": ["pidora", "scientific", "xenserver", "amazon", "oracle", "amzn",
                            "almalinux", "rocky"],
                    "Dnf": ["fedora", "rhel", "centos", "mageia", "nobara"],
                    "Brew": ["Darwin"],
                    "PacMan": ["arch", "manjaro", "msys2", "endeavouros"],
                    "Chocolatey": ["Windows"],
                    "Zypper": ["opensuse", "sles"],
                    "Pkg": ["freebsd"],
                    "Pkgutil": ["Solaris"]}

class SoftConfigRecipe(ConanFile):
    name = "softinstall"
    version = "0.1"
    package_type = "build-scripts"

    # 个人信息
    license = "MIT"
    author = "<OSmile> <whghcyx@outlook.com>"
    url = "https://whg555.github.io"
    description = "readme description"
    topics = ("<Put some tag here>", "<here>", "<and here>")

    # 二进制配置
    settings = "os", "compiler", "build_type", "arch"

    # 针对特定系统的安装包
    packages = {
        "ubuntu" :  {
            "default" : ["apache2-utils"], # 当前系统通用的包
            "20" : ["apache2-utils"], # 特定版本号的包
        },
        "kylin" : {
            "default" : ["apache2-utils"], # 当前系统通用的包
            "v10" :  ["apache2-utils"], # 当前系统通用的包
        },
        "default" : {
            "default" : ["apache2-utils"]
        }
    }

    def init(self):
        '''
        <1>conan create .
        <3>conan create .
        <1>conan install .
        :return:
        '''
        # 判断函数运行的时间
        self.starttime = datetime.now()
        # 判断函数调用顺序的变量
        if not hasattr(self, "runfunnum"):
            self.runfunnum = 0
        print("\033[43;34mOSmile-->", "init", "<" + str(datetime.now() - self.starttime) +  ">", "\033[0m")
        # 更新当前函数调用的
        self.runfunnum += 1
        print("\033[43;34mOSmile-->", self.runfunnum, "\033[0m")
        # 创建缓存目录
        # self.tmppath = tempfile.mkdtemp()
        self.tmppath = os.path.join(os.path.expanduser("~"), "conantmp")
        os.makedirs(self.tmppath, exist_ok=True)

        # 获取系统版本信息
        os_name = platform.system()
        self.os_name = self.os_version = self.os_base = ""
        self.os_base = os_name
        if os_name in ["Linux", "FreeBSD"]:
            import distro
            self.os_name = distro.id() or os_name
            self.os_version = distro.version(best=True).split(".")[0]
        # elif os_name == "Windows" and self.settings.get_safe("os.subsystem") == "msys2":
        elif os_name == "Windows":
            self.os_name = "msys2"
            self.os_version = ""
        print("System   -->", self.os_base)
        print("OSSystem -->", self.os_name)
        print("Version  -->", self.os_version)
        print("TmpPath  -->", self.tmppath)

    def config_options(self):
        '''
        针对系统，对配置命令做一些修改
        <4>conan create .
        <2>conan install .
        <test><1>conan create .
        '''

        print("\033[43;34mOSmile-->", "config_options", "<" + str(datetime.now() - self.starttime) + ">", "\033[0m")
        pprint(self.settings.values_list)
        # pprint(self.serialize())
        # print("self.conf", self.conf)
        print("ARCH", self.settings.get_safe("arch"))
        # print("self.conf", self.conf.keys())

    def configure(self):
        '''
        <5>conan create .
        <3>conan install .
        <test><2>conan create .
        '''
        print("\033[43;34mOSmile-->", "configure", "<" + str(datetime.now() - self.starttime) + ">", "\033[0m")
        if self.os_name == "kylin":
            self.conf.define("tools.system.package_manager:tool", "apt-get")
        self.conf.define("tools.system.package_manager:mode", "install")
        self.conf.define("tools.system.package_manager:sudo", True)

    def system_requirements(self):
        '''
        安装需要的软件
        <10>conan create .
        <8>conan install .
        <test><4>conan create .
        '''
        print("\033[43;34mOSmile-->", "system_requirements", "<" + str(datetime.now() - self.starttime) + ">", "\033[0m")
        if platform.system() in ["Linux", "FreeBSD"]:
            # 获取编译工具
            for tool, distros in manager_mapping.items():
                if self.os_name in distros:
                    break
            # 查找需要安装的包
            os_name_key = self.os_name if (self.os_name in self.packages.keys()) else "default"
            os_version_key = self.os_version if (self.os_version in self.packages[os_name_key].keys()) else "default"
            softs = self.packages.get(os_name_key).get(os_version_key)
            print("安装软件包-->", softs)
            softtool = getattr(package_manager, tool)(self)
            softtool.install(softs, update=False, check=True)
        elif platform.system() == "Windows" and self.settings.get_safe("os.subsystem") == "msys2":
            os_name = "msys2"

        self.run('sudo pip3 install "pypiserver[passlib]"')
        self.run('sudo pip3 install twine')

    def generate(self):
        '''
        配置已经安装的软件
        <13>conan create .
        <9>conan install .
        '''
        print("\033[43;34mOSmile-->", "generate", "<" + str(datetime.now() - self.starttime) + ">", "\033[0m")
        self.run("sudo mkdir /data/pypi -p", ignore_errors=False)
        self.run(f"sudo chown {os.getlogin()}:{os.getlogin()} /data/pypi", ignore_errors=False)
        self.run("mkdir /data/pypi/data -p", ignore_errors=False)
        # 生成密码文件
        self.run("htpasswd -sc htpasswd.txt osmile", cwd="/data/pypi", ignore_errors=False)
        # 创建启动脚本
        self.run("echo 'echo pypi-server run -p 51000 -P htpasswd.txt data/' > /data/pypi/start-server.sh")
        self.run("echo pypi-server run -p 51000 -P htpasswd.txt data/ >> /data/pypi/start-server.sh")
        self.run("chmod +x /data/pypi/start-server.sh")

        serviceconfig = f"""[Unit]
Description=Pypi Service
After=network.target

[Service]
ExecStart=/usr/local/bin/pypi-server run -p 51000 -P htpasswd.txt data/
Restart=always
User={os.getlogin()}
Group={os.getlogin()}
WorkingDirectory=/data/pypi

[Install]
WantedBy=multi-user.target
        """
        with open("/data/pypi/pypi.service", "x", encoding="utf-8") as f:
            f.write(serviceconfig)
        self.run("sudo cp /data/pypi/pypi.service /etc/systemd/system/pypi.service")
        self.run("sudo systemctl daemon-reload")
        self.run("sudo systemctl enable pypi.service")
        self.run("sudo systemctl start pypi.service")
        self.run("sudo systemctl status pypi.service")

        if os.path.exists(self.tmppath):
            # 删除缓存目录
            shutil.rmtree(self.tmppath)

    def finalize(self):
        '''
        <16>conan create .
        :return:
        '''
        print("\033[43;34mOSmile-->", "finalize", "<" + str(datetime.now() - self.starttime) +  ">", "\033[0m")
        if os.path.exists(self.tmppath):
            # 删除缓存目录
            shutil.rmtree(self.tmppath)
